package org.example.commond.handler.room;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.CharUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import lombok.extern.slf4j.Slf4j;
import org.example.commond.AbstractCmdHandler;
import org.example.commond.CommandManager;
import org.example.commond.handler.message.ChatReqHandler;
import org.example.component.UserInfo;
import org.example.config.Chat;
import org.example.config.Im;
import org.example.config.ImConfig;
import org.example.enums.CommandEnum;
import org.example.enums.RoomRoleEnum;
import org.example.packets.bean.Group;
import org.example.packets.bean.User;
import org.example.packets.bean.UserGroup;
import org.example.packets.handler.message.ChatReqBody;
import org.example.packets.handler.room.JoinGroupNotifyBody;
import org.example.packets.handler.system.RespBody;
import org.example.packets.handler.user.GroupUser;
import org.example.util.ChannelContextUtil;
import org.example.util.JsonUtil;
import org.tio.core.ChannelContext;
import org.tio.core.Tio;
import org.tio.core.intf.Packet;
import org.tio.websocket.common.WsRequest;
import org.tio.websocket.common.WsResponse;

import java.util.List;
import java.util.stream.Collectors;

import static com.mongodb.client.model.Filters.and;
import static com.mongodb.client.model.Filters.in;

@Slf4j
public class JoinGroupReqHandler extends AbstractCmdHandler {

    @Override
    public CommandEnum command() {
        return CommandEnum.COMMAND_JOIN_GROUP_REQ;
    }

    @Override
    public WsResponse handler(Packet packet, ChannelContext channelContext) {

        // 转换为加入群组消息
        JoinGroupNotifyBody join = JsonUtil.format(packet,JoinGroupNotifyBody.class);
        // 异常判断: 如果加入的用户为空, 则返回
        if (CollUtil.isEmpty(join.getUsers())) {
            return null;
        }

        // 如果群组头像是空的， 那么就是邀请事件
        if (StrUtil.isBlank(join.getGroup().getAvatar()) && !Boolean.TRUE.equals(join.getGroup().getIsFriend())) {
            Group userGroup = UserInfo.group(join.getGroup().getRoomId());
            join.setGroup(userGroup);
        }

        // 好友的情况下
        for (GroupUser user : join.getUsers()) {
            User userInfo = ImConfig.userListener().onGetUser(user.getId());
            if (null == user.getRole() && !join.getGroup().getIsFriend()) {
                user.setRole(RoomRoleEnum.GENERAL);
            }
            BeanUtil.copyProperties(userInfo, user, "role");
            // 持久化到数据库
            userGroupService.addGroupUser(join.getGroup().getRoomId(), user.getId(), user.getRole(), join.getGroup().getIsFriend());
        }

        log.info("加入群组消息：" + JSON.toJSONString(join, SerializerFeature.DisableCircularReferenceDetect));

        List<UserGroup> userGroupList = userGroupService.getGroupUsers(join.getGroup().getRoomId());

        for (UserGroup userGroup : userGroupList) {

            Group group = userGroupService.getUserGroup(join.getGroup().getRoomId(), userGroup.getUserId(), userGroupList);
            group.setUnreadCount(0);
            for (GroupUser user : group.getUsers()) {
                User userInfo = ImConfig.userListener().onGetUser(user.getId());
                BeanUtil.copyProperties(userInfo, user, "role");

                // 如果是群组, 并且ID不等于当前用户, 并且房间名为空 说明就是对方且没有备注, 那么改名字咯
                if (group.getIsFriend() && StrUtil.isBlank(group.getRoomName()) && !userInfo.getId().equals(userGroup.getUserId())) {
                    group.setFriendId(userInfo.getId());
                    group.setAvatar(userInfo.getAvatar());
                    group.setRoomName(userInfo.getUsername());
                }
            }

            List<ChannelContext> channelByUserId = ChannelContextUtil.contextList(userGroup.getUserId());
            for (ChannelContext context : channelByUserId) {
                Tio.bindGroup(context, group.getRoomId());

                WsResponse wsResponse = WsResponse.fromText(RespBody.success(CommandEnum.COMMAND_JOIN_GROUP_NOTIFY_RESP, group), Im.CHARSET);
                Im.sendToGroup(group.getRoomId(), wsResponse);
            }
        }

        if (!join.getGroup().getIsFriend()) {
            // 发送加入群聊消息
            User nowUser = UserInfo.user();
            ChatReqHandler command = (ChatReqHandler) CommandManager.getCommand(CommandEnum.COMMAND_CHAT_REQ);

            String collect = join.getUsers().stream().map(GroupUser::getUsername).collect(Collectors.joining("、"));
            String msg = (join.getUsers().size() == 1 && nowUser.getId().equals(join.getUsers().get(0).getId()))
                    ? StrUtil.format("{}{}{} 通过群组搜索加入群聊", CharUtil.DOUBLE_QUOTES, collect, CharUtil.DOUBLE_QUOTES)
                    : StrUtil.format("{}{} 邀请 {}{} 加入群聊", CharUtil.DOUBLE_QUOTES, nowUser.getUsername(), collect, CharUtil.DOUBLE_QUOTES);

            ChatReqBody chatReqBody = ChatReqBody.buildSystem(join.getGroup().getRoomId(), nowUser.getId(), msg);
            WsRequest wsRequest = WsRequest.fromText(JSON.toJSONString(chatReqBody, SerializerFeature.DisableCircularReferenceDetect), Im.CHARSET);
            command.handler(wsRequest, channelContext);

        }

        return null;
    }
}
